<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>百度网盘文件同步助手 - 多选版</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary: #1E9FFF;
            --primary-light: #a0d7ff;
            --success: #5FB878;
            --warning: #FFB800;
            --danger: #FF5722;
            --dark: #394456;
            --light: #f8f9fa;
            --gray: #6c757d;
            --border: #e9ecef;
            --file-color: #1E9FFF;
            --folder-color: #FFB800;
            --select-bg: rgba(30, 159, 255, 0.1);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #e4e7f4 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            padding-top: 20px;
        }

        .header h1 {
            font-size: 2.5rem;
            color: #2c3e50;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.1rem;
            color: #7f8c8d;
            max-width: 700px;
            margin: 0 auto;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 25px;
        }

        @media (max-width: 768px) {
            .container {
                grid-template-columns: 1fr;
            }
        }

        .card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
            overflow: hidden;
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        .card-header {
            background: linear-gradient(135deg, var(--primary) 0%, #2980b9 100%);
            color: white;
            padding: 18px 25px;
            font-size: 1.4rem;
            display: flex;
            align-items: center;
            gap: 12px;
            font-weight: 600;
        }

        .card-body {
            padding: 25px;
            flex-grow: 1;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .file-explorer {
            border: 1px solid var(--border);
            border-radius: 8px;
            overflow: hidden;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }

        .explorer-header {
            padding: 15px;
            background: var(--light);
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid var(--border);
        }

        .path-info {
            display: flex;
            align-items: center;
            font-size: 0.95rem;
            color: var(--gray);
        }

        .path-info i {
            margin-right: 8px;
        }

        .actions {
            display: flex;
            gap: 10px;
        }

        .btn {
            padding: 8px 15px;
            border-radius: 6px;
            border: none;
            background: var(--light);
            color: var(--gray);
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 5px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .btn:hover {
            background: var(--primary-light);
            color: var(--primary);
        }

        .btn-primary {
            background: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background: #0d8aee;
        }

        .btn-select-all {
            background: rgba(255, 184, 0, 0.1);
            color: var(--warning);
            border: 1px solid rgba(255, 184, 0, 0.3);
        }

        .explorer-body {
            flex-grow: 1;
            overflow-y: auto;
            height: 300px;
            padding: 10px 5px;
        }

        .directory-content {
            list-style: none;
        }

        .file-item {
            padding: 10px 15px;
            display: flex;
            align-items: center;
            border-radius: 6px;
            cursor: pointer;
            transition: all 0.2s;
            position: relative;
        }

        .file-item.selected {
            background: var(--select-bg);
            border: 1px solid var(--primary);
        }

        .file-item:hover {
            background: rgba(30, 159, 255, 0.08);
        }

        .file-icon {
            width: 30px;
            height: 30px;
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
        }

        .file-icon.file {
            background: rgba(30, 159, 255, 0.15);
            color: var(--file-color);
        }

        .file-icon.folder {
            background: rgba(255, 184, 0, 0.15);
            color: var(--folder-color);
        }

        .file-name {
            flex-grow: 1;
            font-weight: 500;
        }

        .file-info {
            font-size: 0.85rem;
            color: var(--gray);
            margin-right: 10px;
            min-width: 70px;
            text-align: right;
        }

        .checkbox {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            width: 18px;
            height: 18px;
            border: 2px solid var(--gray);
            border-radius: 3px;
            cursor: pointer;
        }

        .checkbox.checked:after {
            content: '\f00c';
            font-family: "Font Awesome 5 Free";
            font-weight: 900;
            font-size: 12px;
            position: absolute;
            left: 1px;
            top: 0px;
            color: white;
        }

        .checkbox.checked {
            background: var(--primary);
            border-color: var(--primary);
        }

        .selected-section {
            margin-top: 20px;
        }

        .section-title {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-size: 1.1rem;
            margin-bottom: 15px;
            color: var(--dark);
        }

        .section-title-left {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .selection-count {
            background: var(--primary);
            color: white;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8rem;
        }

        .selected-items {
            border: 1px dashed var(--primary);
            border-radius: 8px;
            padding: 15px;
            background: rgba(30, 159, 255, 0.03);
            min-height: 100px;
            max-height: 200px;
            overflow-y: auto;
        }

        .selected-item {
            display: flex;
            justify-content: space-between;
            padding: 10px;
            margin-bottom: 8px;
            background: white;
            border-radius: 6px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.05);
            border-left: 3px solid var(--primary);
        }

        .item-details {
            display: flex;
            flex-direction: column;
            flex: 1;
            min-width: 0;
        }

        .item-name {
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .item-type {
            font-size: 0.75rem;
            padding: 2px 8px;
            border-radius: 10px;
            display: inline-block;
        }

        .item-file {
            background: rgba(30, 159, 255, 0.15);
            color: var(--file-color);
        }

        .item-folder {
            background: rgba(255, 184, 0, 0.15);
            color: var(--folder-color);
        }

        .item-path {
            font-size: 0.85rem;
            color: var(--gray);
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-top: 4px;
        }

        .remove-btn {
            color: var(--danger);
            cursor: pointer;
            padding: 0 8px;
            display: flex;
            align-items: center;
        }

        .empty-state {
            text-align: center;
            padding: 30px 0;
            color: var(--gray);
        }

        .empty-state i {
            font-size: 3rem;
            color: #dce1e6;
            margin-bottom: 15px;
        }

        .upload-section {
            padding: 20px 0;
        }

        .status-bar {
            background: var(--light);
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
            border: 1px solid var(--border);
        }

        .progress-container {
            display: none;
        }

        .progress-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }

        .progress-wrapper {
            height: 12px;
            background: #e9ecef;
            border-radius: 6px;
            overflow: hidden;
        }

        .progress-bar {
            height: 100%;
            background: linear-gradient(to right, var(--primary), var(--success));
            border-radius: 6px;
            width: 0%;
            transition: width 0.4s ease;
        }

        .file-progress-info {
            display: flex;
            justify-content: space-between;
            font-size: 0.9rem;
            color: var(--gray);
            margin-top: 5px;
        }

        .recursive-info {
            background: rgba(95, 184, 120, 0.1);
            border-radius: 6px;
            padding: 10px;
            margin-top: 15px;
            font-size: 0.9rem;
            color: var(--success);
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .upload-actions {
            display: flex;
            justify-content: center;
            gap: 15px;
            margin-top: 25px;
            padding-top: 15px;
            border-top: 1px solid var(--border);
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            border-radius: 8px;
            background: white;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            gap: 10px;
            transform: translateX(150%);
            transition: transform 0.4s ease;
            z-index: 1000;
        }

        .notification.show {
            transform: translateX(0);
        }

        .notification i {
            font-size: 1.5rem;
        }

        .notification-success {
            color: var(--success);
            border-left: 4px solid var(--success);
        }

        .notification-error {
            color: var(--danger);
            border-left: 4px solid var(--danger);
        }

        .spinner {
            display: inline-block;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .breadcrumb {
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            margin-bottom: 10px;
            font-size: 0.9rem;
        }

        .breadcrumb-item {
            cursor: pointer;
            color: var(--primary);
            display: flex;
            align-items: center;
        }

        .breadcrumb-item::after {
            content: '/';
            margin: 0 8px;
            color: var(--gray);
        }

        .breadcrumb-item:last-child {
            color: var(--dark);
            font-weight: 500;
            cursor: default;
        }

        .breadcrumb-item:last-child::after {
            content: none;
        }

        .pan-dir-input {
            display: flex;
            gap: 10px;
            margin-bottom: 15px;
        }

        .pan-dir-input input {
            flex: 1;
            padding: 10px 15px;
            border: 1px solid var(--border);
            border-radius: 6px;
            font-size: 1rem;
        }

        .pan-dir-input button {
            padding: 0 15px;
            border-radius: 6px;
            background: var(--primary);
            color: white;
            border: none;
            cursor: pointer;
        }

        .pan-example {
            font-size: 0.9rem;
            color: var(--gray);
            margin-bottom: 15px;
        }

        .websocket-status {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 5px 10px;
            background: #f8f9fa;
            border-radius: 4px;
            font-size: 0.9rem;
            margin-bottom: 15px;
        }

        .ws-connected {
            color: var(--success);
        }

        .ws-disconnected {
            color: var(--danger);
        }
    </style>
</head>
<body>
<div class="header">
    <h1><i class="fas fa-cloud-upload-alt"></i>百度网盘文件同步助手</h1>
    <p>支持多选文件/目录、实时WebSocket通知</p>
</div>

<div class="container">
    <!-- 左侧：本地文件浏览器 -->
    <div class="card">
        <div class="card-header">
            <i class="fas fa-folder"></i>本地文件系统
        </div>
        <div class="card-body">
            <!-- 路径面包屑导航 -->
            <div class="breadcrumb" id="localBreadcrumb">
                <div class="breadcrumb-item" onclick="navigateToLocal('/')">
                    <i class="fas fa-home"></i> 根目录
                </div>
            </div>

            <div class="file-explorer">
                <div class="explorer-header">
                    <div class="path-info">
                        <i class="fas fa-folder-open"></i>
                        <span id="localPath">/</span>
                    </div>
                    <div class="actions">
                        <button class="btn" id="btnBackLocal" disabled>
                            <i class="fas fa-arrow-left"></i> 返回上级
                        </button>
                        <button class="btn btn-select-all" id="btnSelectAll">
                            <i class="fas fa-check-square"></i> 全选
                        </button>
                    </div>
                </div>
                <div class="explorer-body" id="localExplorer">
                    <div class="empty-state">
                        <i class="fas fa-spinner spinner"></i>
                        <p>正在加载本地文件系统...</p>
                    </div>
                </div>
            </div>

            <div class="selected-section">
                <div class="section-title">
                    <div class="section-title-left">
                        <i class="fas fa-check-circle"></i>
                        <span>已选择的项目</span>
                        <div class="selection-count" id="selectedCount">0</div>
                    </div>
                    <button class="btn" id="btnClearSelection">
                        <i class="fas fa-times"></i> 清除
                    </button>
                </div>
                <div class="selected-items" id="selectedItems">
                    <div class="empty-state">
                        <i class="fas fa-archive"></i>
                        <p>请选择要上传的文件或目录</p>
                    </div>
                </div>

                <div class="recursive-info">
                    <i class="fas fa-info-circle"></i>
                    <span>如果选择目录，将递归同步其所有子目录和文件</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 右侧：百度网盘设置 -->
    <div class="card">
        <div class="card-header">
            <i class="fas fa-cloud"></i>百度网盘设置
        </div>
        <div class="card-body">
            <div class="websocket-status" id="wsStatus">
                <i class="fas fa-plug"></i>
                <span>WebSocket状态: <span id="wsState">正在连接...</span></span>
            </div>

            <div class="pan-dir-input">
                <input type="text" id="panDir" placeholder="请输入百度网盘目标路径" value="/">
                <button id="btnSetPanDir">
                    <i class="fas fa-check"></i> 设置
                </button>
            </div>
            <div class="pan-example">
                <i class="fas fa-info-circle"></i> 示例格式: /我的资源/文档 或 /备份2023
            </div>

            <div class="upload-section">
                <div class="status-bar">
                    <div class="progress-container" id="progressContainer">
                        <div class="progress-info">
                            <span>上传进度</span>
                            <span id="progressPercent">0%</span>
                        </div>
                        <div class="progress-wrapper">
                            <div class="progress-bar" id="progressBar"></div>
                        </div>
                        <div class="file-progress-info">
                            <span id="currentFile">准备开始同步...</span>
                            <span id="fileCounter">0/0</span>
                        </div>
                    </div>

                    <div id="statusMessage">
                        请选择要上传的文件/目录并设置目标路径
                    </div>
                </div>

                <div class="upload-actions">
                    <button class="btn btn-primary" id="btnUpload">
                        <i class="fas fa-sync-alt"></i> 开始上传
                    </button>
                    <button class="btn" id="btnReset">
                        <i class="fas fa-redo"></i> 重置
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="notification notification-success" id="successNotification">
    <i class="fas fa-check-circle"></i>
    <div id="successMessage">文件已成功上传到百度网盘！</div>
</div>

<div class="notification notification-error" id="errorNotification">
    <i class="fas fa-exclamation-triangle"></i>
    <div id="errorMessage">上传过程中发生错误！</div>
</div>

<script>
    // 全局变量
    const API = {
        localFiles: "/baidu/pan/file/upload/nodes",
        upload: "/baidu/pan/file/upload/upload"
    };
    const WS_URL = "ws://" + window.location.hostname + ":9990/websocket";

    let selectedItems = [];
    let panDir = "/"; // 默认百度网盘目录
    let currentLocalPath = '/';
    let uploadQueue = [];
    let currentUpload = 0;
    let totalUploads = 0;
    let wsConnection = null;
    let wsConnected = false;

    // 页面加载完成后执行
    document.addEventListener('DOMContentLoaded', function() {
        // 初始化文件浏览器
        loadLocalFiles('/');

        // 绑定按钮事件
        document.getElementById('btnBackLocal').addEventListener('click', goBackLocal);
        document.getElementById('btnUpload').addEventListener('click', startUpload);
        document.getElementById('btnReset').addEventListener('click', resetSelection);
        document.getElementById('btnSelectAll').addEventListener('click', toggleSelectAll);
        document.getElementById('btnClearSelection').addEventListener('click', clearSelection);
        document.getElementById('btnSetPanDir').addEventListener('click', setPanDir);

        // 设置默认网盘路径
        document.getElementById('panDir').value = panDir;

        // 初始化WebSocket连接
        initWebSocket();
    });

    // 初始化WebSocket连接
    function initWebSocket() {
        try {
            wsConnection = new WebSocket(WS_URL);

            wsConnection.onopen = function() {
                wsConnected = true;
                updateWsStatus("已连接", "ws-connected");
                showNotification('success', 'WebSocket连接已建立，准备接收实时通知');
            };

            wsConnection.onmessage = function(event) {
                handleWsMessage(event.data);
            };

            wsConnection.onclose = function() {
                wsConnected = false;
                updateWsStatus("已断开", "ws-disconnected");

                // 尝试重新连接
                setTimeout(initWebSocket, 3000);
            };

            wsConnection.onerror = function(error) {
                console.error("WebSocket错误:", error);
                updateWsStatus("连接错误", "ws-disconnected");
            };
        } catch (error) {
            console.error("创建WebSocket失败:", error);
            updateWsStatus("初始化失败", "ws-disconnected");
        }
    }

    // 更新WebSocket状态显示
    function updateWsStatus(text, className) {
        const statusEl = document.getElementById('wsStatus');
        const stateEl = document.getElementById('wsState');

        stateEl.textContent = text;
        statusEl.className = `websocket-status ${className}`;
    }

    // 处理WebSocket消息
    function handleWsMessage(data) {
        try {
            const message = JSON.parse(data);
            console.log("收到WebSocket消息:", message);

            switch (message.type) {
                case 'progress':
                    updateUploadProgress(message);
                    break;
                case 'success':
                    showNotification('success', message.content || '操作成功');
                    break;
                case 'error':
                    showNotification('error', message.content || '操作失败');
                    break;
                case 'info':
                    // 更新当前文件信息
                    document.getElementById('currentFile').textContent = message.content;
                    break;
                default:
                    console.log('未知消息类型:', message);
            }
        } catch (error) {
            console.error("解析WebSocket消息失败:", error);
        }
    }

    // 设置百度网盘目录
    function setPanDir() {
        const newDir = document.getElementById('panDir').value.trim();
        if (newDir) {
            panDir = newDir;
            showNotification('success', `目标路径已设置为: ${panDir}`);
        } else {
            showNotification('error', '请输入有效的目标路径');
        }
    }

    // 加载本地文件
    function loadLocalFiles(path) {
        currentLocalPath = path || '/';
        const url = `${API.localFiles}?path=${encodeURIComponent(currentLocalPath)}`;

        document.getElementById('localPath').textContent = currentLocalPath;
        document.getElementById('btnBackLocal').disabled = currentLocalPath === '/';

        // 更新面包屑导航
        updateLocalBreadcrumb(currentLocalPath);

        document.getElementById('localExplorer').innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-spinner spinner"></i>
                    <p>正在加载目录内容...</p>
                </div>
            `;

        // 模拟API响应
        setTimeout(() => {
            // 在实际应用中应替换为真实API调用
            const files = generateSampleFiles(path);
            renderLocalFiles(files);
        }, 500);
    }

    // 更新本地面包屑导航
    function updateLocalBreadcrumb(path) {
        const breadcrumb = document.getElementById('localBreadcrumb');
        breadcrumb.innerHTML = '';

        // 添加根目录
        breadcrumb.innerHTML += `
                <div class="breadcrumb-item" onclick="navigateToLocal('/')">
                    <i class="fas fa-home"></i> 根目录
                </div>
            `;

        // 如果不在根目录，添加路径各部分
        if (path && path !== '/') {
            const parts = path.split('/').filter(p => p);
            let currentPath = '';

            parts.forEach((part, index) => {
                currentPath += '/' + part;
                const isLast = index === parts.length - 1;

                if (!isLast) {
                    breadcrumb.innerHTML += `
                            <div class="breadcrumb-item" onclick="navigateToLocal('${currentPath}')">
                                ${part}
                            </div>
                        `;
                } else {
                    breadcrumb.innerHTML += `
                            <div class="breadcrumb-item">${part}</div>
                        `;
                }
            });
        }
    }

    // 导航到本地目录
    function navigateToLocal(path) {
        loadLocalFiles(path);
    }

    // 生成示例文件列表
    function generateSampleFiles(path) {
        const folders = ["文档", "图片", "音乐", "视频", "下载"];
        const files = {
            "文档": ["报告.docx", "简历.pdf", "笔记.md"],
            "图片": ["风景.jpg", "头像.png", "相册封面.webp"],
            "音乐": ["歌曲.mp3", "伴奏.wav", "铃声.m4a"],
            "视频": ["电影.mp4", "教程.mov", "直播录像.flv"],
            "下载": ["安装包.exe", "压缩包.zip", "软件.dmg"],
            "/": ["系统文件", "用户文件", "共享资源"]
        };

        const isRoot = path === '/';
        const pathKey = isRoot ? '/' : path.split('/').pop() || '';

        const result = [];

        // 在非根目录添加返回上级项
        if (!isRoot) {
            result.push({
                id: "up",
                name: "返回上级",
                isDir: true,
                size: 0
            });
        }

        // 添加目录
        folders.forEach(folder => {
            result.push({
                id: `${path}/${folder}`,
                name: folder,
                isDir: true,
                size: Math.floor(Math.random() * 1024)
            });
        });

        // 添加文件
        if (files[pathKey]) {
            files[pathKey].forEach(file => {
                result.push({
                    id: `${path}/${file}`,
                    name: file,
                    isDir: false,
                    size: Math.floor(Math.random() * 10240000) + 10000
                });
            });
        }

        return result;
    }

    // 渲染本地文件
    function renderLocalFiles(items) {
        const explorer = document.getElementById('localExplorer');

        if (!items || items.length === 0) {
            explorer.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-folder-open"></i>
                        <p>此目录下没有文件或目录</p>
                    </div>
                `;
            return;
        }

        let html = '<ul class="directory-content">';

        // 添加文件和目录项
        items.forEach(item => {
            const isDir = item.isDir;
            const isUp = item.name === "返回上级";
            const iconClass = isDir ? "folder" : "file";
            const icon = isUp ? "level-up-alt" : (isDir ? "folder" : "file");
            const isSelected = selectedItems.some(i => i.id === item.id);

            const itemClass = isSelected ? "file-item selected" : "file-item";

            // 为目录项添加导航功能
            const onClick = isDir ?
                `onclick="navigateToLocal('${isUp ? getParentPath(currentLocalPath) : item.id}')"` :
                `onclick="toggleItemSelection('${item.id}', '${item.name}', '${isDir ? 'folder' : 'file'}')"`;

            html += `
                    <li class="${itemClass}" id="item-${item.id}" ${onClick}>
                        <div class="file-icon ${iconClass}">
                            <i class="fas fa-${icon}"></i>
                        </div>
                        <div class="file-name">${item.name}</div>
                        <div class="file-info">${isDir ? '' : formatBytes(item.size || 0)}</div>
                        <div class="checkbox ${isSelected ? 'checked' : ''}" onclick="event.stopPropagation(); toggleItemSelection('${item.id}', '${item.name}', '${isDir ? 'folder' : 'file'}')"></div>
                    </li>
                `;
        });

        html += '</ul>';
        explorer.innerHTML = html;
    }

    // 格式字节
    function formatBytes(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
    }

    // 选择文件或目录
    function toggleItemSelection(id, name, type) {
        const itemIndex = selectedItems.findIndex(item => item.id === id);

        if (itemIndex === -1) {
            // 添加新选择
            selectedItems.push({
                id: id,
                name: name,
                type: type,
                path: id
            });
        } else {
            // 移除选择
            selectedItems.splice(itemIndex, 1);
        }

        const itemEl = document.getElementById(`item-${id}`);
        if (itemEl) {
            itemEl.classList.toggle("selected");
            const checkbox = itemEl.querySelector('.checkbox');
            if (checkbox) {
                checkbox.classList.toggle('checked');
            }
        }

        renderSelectedItems();
        updateSelectionCount();
    }

    // 渲染已选项目
    function renderSelectedItems() {
        const container = document.getElementById('selectedItems');

        if (!selectedItems || selectedItems.length === 0) {
            container.innerHTML = `
                    <div class="empty-state">
                        <i class="fas fa-archive"></i>
                        <p>请选择要上传的文件或目录</p>
                    </div>
                `;
            return;
        }

        container.innerHTML = '';

        selectedItems.forEach(item => {
            const itemType = item.type === 'file' ? '文件' : '目录';
            const typeClass = item.type === 'file' ? 'item-file' : 'item-folder';

            const div = document.createElement('div');
            div.className = 'selected-item';
            div.innerHTML = `
                    <div class="item-details">
                        <div class="item-name">
                            <i class="fas fa-${item.type === 'file' ? 'file' : 'folder'}"></i>
                            ${item.name}
                            <span class="item-type ${typeClass}">${itemType}</span>
                        </div>
                        <div class="item-path">${item.path}</div>
                    </div>
                    <div class="remove-btn" onclick="removeSelectedItem('${item.id}')">
                        <i class="fas fa-times"></i>
                    </div>
                `;
            container.appendChild(div);
        });
    }

    // 更新选择数量
    function updateSelectionCount() {
        document.getElementById('selectedCount').textContent = selectedItems.length;
    }

    // 删除选择项目
    function removeSelectedItem(id) {
        selectedItems = selectedItems.filter(item => item.id !== id);

        // 更新列表中的选择状态
        const itemEl = document.getElementById(`item-${id}`);
        if (itemEl) {
            itemEl.classList.remove("selected");
            const checkbox = itemEl.querySelector('.checkbox');
            if (checkbox) {
                checkbox.classList.remove('checked');
            }
        }

        renderSelectedItems();
        updateSelectionCount();
    }

    // 清除所有选择
    function clearSelection() {
        // 清除选择状态
        selectedItems.forEach(item => {
            const itemEl = document.getElementById(`item-${item.id}`);
            if (itemEl) {
                itemEl.classList.remove("selected");
                const checkbox = itemEl.querySelector('.checkbox');
                if (checkbox) {
                    checkbox.classList.remove('checked');
                }
            }
        });

        selectedItems = [];
        renderSelectedItems();
        updateSelectionCount();
    }

    // 全选/取消全选
    function toggleSelectAll() {
        const items = document.querySelectorAll('#localExplorer .file-item:not(:first-child)');
        if (items.length === 0) return;

        // 检查当前是否全选
        const allSelected = Array.from(items).every(item =>
            selectedItems.some(selected => selected.id === item.id.split('-')[1])
        );

        if (allSelected) {
            // 取消全选
            items.forEach(item => {
                const id = item.id.split('-')[1];
                if (selectedItems.some(i => i.id === id)) {
                    removeSelectedItem(id);
                }
            });
        } else {
            // 全选
            items.forEach(item => {
                if (!item.id.includes('item-')) return;

                const id = item.id.split('-')[1];
                const name = item.querySelector('.file-name').textContent;
                const type = item.querySelector('.file-icon.folder') ? 'folder' : 'file';

                // 如果尚未选择，则添加选择
                if (!selectedItems.some(i => i.id === id)) {
                    selectedItems.push({
                        id: id,
                        name: name,
                        type: type,
                        path: id
                    });
                }
            });
            renderSelectedItems();
            updateSelectionCount();
        }

        // 更新UI
        items.forEach(item => {
            if (!item.id.includes('item-')) return;

            const id = item.id.split('-')[1];
            const isSelected = selectedItems.some(i => i.id === id);

            item.classList.toggle("selected", isSelected);
            const checkbox = item.querySelector('.checkbox');
            if (checkbox) {
                checkbox.classList.toggle('checked', isSelected);
            }
        });
    }

    // 开始上传
    function startUpload() {
        if (selectedItems.length === 0) {
            showNotification('error', '请选择要上传的文件或目录');
            return;
        }

        // 显示进度
        const progressContainer = document.getElementById('progressContainer');
        const statusMessage = document.getElementById('statusMessage');

        progressContainer.style.display = 'block';
        statusMessage.style.display = 'none';

        // 创建上传队列
        uploadQueue = [...selectedItems];
        currentUpload = 0;
        totalUploads = uploadQueue.length;

        // 开始上传第一个项目
        uploadNext();
    }

    // 上传下一个项目
    function uploadNext() {
        if (currentUpload >= totalUploads) {
            // 所有项目上传完成
            document.getElementById('currentFile').textContent = '所有项目上传完成';
            showNotification('success', `成功上传了 ${totalUploads} 个项目`);
            return;
        }

        const item = uploadQueue[currentUpload];
        updateProgress();

        // 构建API URL
        const url = `${API.upload}?panDir=${encodeURIComponent(panDir)}&localFiles=${encodeURIComponent(item.id)}`;

        // 模拟WebSocket通知
        if (wsConnected) {
            const wsMessage = {
                type: "info",
                content: `正在上传${item.type === 'file' ? '文件' : '目录'}: ${item.name}`
            };
            document.getElementById('currentFile').textContent = wsMessage.content;
            wsConnection.send(JSON.stringify(wsMessage));
        } else {
            document.getElementById('currentFile').textContent =
                `正在上传${item.type === 'file' ? '文件' : '目录'}: ${item.name}`;
        }

        // 模拟上传延迟
        setTimeout(() => {
            console.log(`API调用: ${url}`);

            // 在实际应用中应替换为真实API调用
            // fetch(url, {
            //   method: 'POST'
            // })

            // 上传完成后继续下一个
            currentUpload++;
            updateProgress();
            uploadNext();
        }, 2000);
    }

    // 更新上传进度（基于WebSocket消息）
    function updateUploadProgress(message) {
        const percent = message.percent || 0;
        const current = message.current || 0;
        const total = message.total || totalUploads;
        const filename = message.filename || '';

        document.getElementById('progressBar').style.width = `${percent}%`;
        document.getElementById('progressPercent').textContent = `${percent}%`;
        document.getElementById('fileCounter').textContent = `${current}/${total}`;

        if (filename) {
            document.getElementById('currentFile').textContent =
                `上传中: ${filename}`;
        }
    }

    // 手动更新进度（基于当前队列）
    function updateProgress() {
        const percent = Math.round((currentUpload / totalUploads) * 100);
        document.getElementById('progressBar').style.width = `${percent}%`;
        document.getElementById('progressPercent').textContent = `${percent}%`;
        document.getElementById('fileCounter').textContent = `${currentUpload + 1}/${totalUploads}`;
    }

    // 重置选择
    function resetSelection() {
        selectedItems = [];
        uploadQueue = [];
        currentUpload = 0;

        renderSelectedItems();
        updateSelectionCount();

        const progressContainer = document.getElementById('progressContainer');
        const statusMessage = document.getElementById('statusMessage');

        progressContainer.style.display = 'none';
        statusMessage.style.display = 'block';
        document.getElementById('progressBar').style.width = '0%';

        // 重新加载当前路径
        loadLocalFiles(currentLocalPath);

        showNotification('info', '选择已重置');
    }

    // 获取上级目录
    function getParentPath(path) {
        if (!path || path === '/') return '';

        const trimmedPath = path.endsWith('/') ?
            path.slice(0, -1) : path;

        const lastSlashIndex = trimmedPath.lastIndexOf('/');

        if (lastSlashIndex === 0) return '/';
        if (lastSlashIndex > 0) return trimmedPath.substring(0, lastSlashIndex);

        return '';
    }

    // 返回本地文件上级
    function goBackLocal() {
        if (!currentLocalPath || currentLocalPath === '/') return;
        const parentPath = getParentPath(currentLocalPath);
        navigateToLocal(parentPath);
    }

    // 显示通知
    function showNotification(type, message) {
        const notification = type === 'success' ?
            document.getElementById('successNotification') :
            document.getElementById('errorNotification');

        const messageEl = notification.querySelector('div');

        if (!notification) return;

        messageEl.textContent = message;
        notification.classList.add('show');

        setTimeout(() => {
            notification.classList.remove('show');
        }, 3000);
    }
</script>
</body>
</html>